import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Home from '@/views/Home.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录 - 网上书城',
      requiresGuest: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      title: '注册 - 网上书城',
      requiresGuest: true
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页 - 网上书城',
      requiresAuth: true
    }
  },
  {
    path: '/admin',
    name: 'Admin',
    component: Home, // 临时使用Home组件
    meta: {
      title: '管理后台 - 网上书城',
      requiresAuth: true,
      requiresRole: 'admin'
    }
  },
  {
    path: '/merchant',
    name: 'Merchant',
    component: Home, // 临时使用Home组件
    meta: {
      title: '商家中心 - 网上书城',
      requiresAuth: true,
      requiresRole: 'merchant'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 动态导入用户store以避免循环依赖
  const { useUserStore } = await import('@/stores/user')
  const userStore = useUserStore()

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      // 未登录，重定向到登录页
      next('/login')
      return
    }

    // 检查角色权限
    if (to.meta.requiresRole && userStore.userRole !== to.meta.requiresRole) {
      // 权限不足，重定向到首页
      next('/home')
      return
    }
  }

  // 检查是否需要游客状态（已登录用户不能访问登录/注册页）
  if (to.meta.requiresGuest && userStore.isLoggedIn) {
    next('/home')
    return
  }

  next()
})

export default router
